//
//  YYAtmosphereVC.m
//  CollarMicrophone
//
//  Created by Yown on 2024/4/9.
//

#import "YYAtmosphereVC.h"
#import "YYAtmosphereView.h"
#import "YYAtmosphereModel.h"

#import <BIToolModule/NSArray+Helper.h>
#import <BIToolModule/NSString+Network.h>
#import <BIToolModule/BIPlayManager.h>
#import <BINetworkModule/BINetworkManager.h>

//#import <AVFoundation/AVFoundation.h>
#import <Masonry/Masonry.h>

@interface YYAtmosphereVC () <AVAudioPlayerDelegate>

@property (nonatomic) YYAtmosphereView *atomsphereView;
@property (nonatomic) NSMutableArray <YYAtmosphereModel *>*dataArray;

@property (nonatomic) AVAudioPlayer *audioPlayer;

@end

@implementation YYAtmosphereVC

#pragma mark - Life Cycle

+ (void)load {
    [[BIRouteManager sharedInstance] registerCMD:@"atmosphere" objectOrClass:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupPlayMode];
    [self setupDatas];
    [self setupViews];
    [self setupLayouts];
}

- (void)setupPlayMode {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playRepeatSecondsNotification) name:kPlayRepeatSecondsNotification object:nil];
    [[BIPlayManager sharedInstance] launch];
//    AVAudioSession *session = [AVAudioSession sharedInstance];
//    [session setCategory:AVAudioSessionCategoryAmbient withOptions:AVAudioSessionCategoryOptionMixWithOthers error:nil];
//    [session setActive:YES error:nil];
}

- (void)setupDatas {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"atmosphere" ofType:@"json"];
    NSData *data = [NSData dataWithContentsOfFile:path];
    self.dataArray = [NSMutableArray array];
    [self.dataArray addObjectsFromArray:[NSArray modelArrayWithClass:[YYAtmosphereModel class] json:data]];
    
    BINetworkRequest *request = [[BINetworkManager sharedInstance] requestWithPath:@"api/app/ambientSound/all" arguments:nil succeedBlock:^(BINetworkResponse *response) {
        NSArray *modelArray = [NSArray modelArrayWithClass:[YYAtmosphereModel class] json:response.modelValue];
        [self.dataArray addObjectsFromArray:modelArray];
        [self.atomsphereView reloadModelArray:self.dataArray];
    } failureBlock:nil completionBlock:nil];
    request.methodType = kBINetworkGetMethodType;
    request.responseKeyPath = @"data";
    [[BINetworkManager sharedInstance] startRequest:request];
}

- (void)setupViews {
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.yy_navigationItem.title = BILocalizedString(@"tab_atmosphere");

    self.atomsphereView = [YYAtmosphereView view];
    [self.atomsphereView reloadModelArray:self.dataArray];
    @weakify(self);
    self.atomsphereView.clickCellBlock = ^(id value) {
        @strongify(self);
        [self playWithModel:value];
    };
    [self.view addSubview:self.atomsphereView];
}

- (void)setupLayouts {
    [self.atomsphereView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.top.mas_equalTo(BINavigationBarHeight);
    }];
}

#pragma mark - Private Method

- (void)playWithModel:(YYAtmosphereModel *)model {
//    [self.audioPlayer stop];
//
//    NSString *audioFilePath = [[NSBundle mainBundle] pathForResource:model.filename ofType:@"mp3"];
//    NSURL *audioFileURL = [NSURL fileURLWithPath:audioFilePath];
//
//    NSError *error = nil;
//    self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioFileURL error:&error];
//    self.audioPlayer.delegate = self;
//    if (self.audioPlayer) {
//        self.audioPlayer.volume = 1;
//        [self.audioPlayer prepareToPlay];
//        [self.audioPlayer play];
//    }
    [[BIPlayManager sharedInstance] stop];
    if ([NSString isURL:model.filename]) {
        [[BIPlayManager sharedInstance] playWithPath:model.filename];
    } else {
        NSString *audioFilePath = [[NSBundle mainBundle] pathForResource:model.filename ofType:@"mp3"];
        [[BIPlayManager sharedInstance] playWithPath:audioFilePath];
    }
}

//#pragma mark - AVAudioPlayerDelegate

//- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
//    [self.dataArray enumerateObjectsUsingBlock:^(YYAtmosphereModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//        obj.isPlay = NO;
//    }];
//    [self.atomsphereView reloadModelArray:self.dataArray];
//}

#pragma mark - Notification

- (void)playRepeatSecondsNotification {
    if ([BIPlayManager sharedInstance].playState == kBIPlayEndState) {
        [self.dataArray enumerateObjectsUsingBlock:^(YYAtmosphereModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            obj.isPlay = NO;
        }];
        [self.atomsphereView reloadModelArray:self.dataArray];
    }
}

#pragma mark - Replace Super Method

- (void)languageChanged:(NSNotification *)notification {
    self.yy_navigationItem.title = BILocalizedString(@"tab_atmosphere");

    [self.atomsphereView reloadModelArray:self.dataArray];
}

@end
